package com.pengtu.gsj.dao.hibernate;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.hibernate.HibernateException;
import org.hibernate.event.internal.DefaultSaveOrUpdateEventListener;
import org.hibernate.event.spi.SaveOrUpdateEvent;

import com.pengtu.gsj.entity.base.IdEntity;
import com.pengtu.gsj.utils.Constants;
import com.pengtu.gsj.utils.DateUtils;
import com.pengtu.gsj.utils.UserUtils;

/**
 * @author zl
 * @version 创建时间：2017年3月30日 上午11:16:47
 *          在hibernate执行saveOrUpdate()时,自动为IdEntity的子类添加信息.
 */
public class AccountSaveUpdateEventListener extends
		DefaultSaveOrUpdateEventListener {

	private static final long serialVersionUID = -5890362089838366308L;
	final Logger logger = Logger.getLogger("dbListener");

	@Override
	public void onSaveOrUpdate(SaveOrUpdateEvent event)
			throws HibernateException {
		Object object = event.getObject();
		if (object instanceof IdEntity) {
			IdEntity entity = (IdEntity) object;
			if (StringUtils.isEmpty(entity.getId())) {
				entity.setId(null);
				entity.setDelFlag(Constants.DELFLAG_IN);
				entity.setCreateDate(DateUtils.getCurrentDate());
			} else {
				if (StringUtils.isEmpty(entity.getDelFlag())) {
					entity.setDelFlag(Constants.DELFLAG_IN);
				} else if (!entity.getDelFlag().equals(Constants.DELFLAG_UN)) {
					entity.setDelFlag(Constants.DELFLAG_IN);
				}
			}
		}
		// super.onSaveOrUpdate(event);

		/*
		 * log日志
		 */
		String username = UserUtils.getName();
		String classname = object.getClass().getName();
		if (classname.indexOf(".") != -1) {
			classname = classname.substring(classname.lastIndexOf(".") + 1,
					classname.length());
		}
		String id = com.pengtu.gsj.utils.StringUtils.getUUID();
		String opid = "";
		String optype = "";
		String delFlag = "";
		if (object instanceof IdEntity) {
			IdEntity entity = (IdEntity) object;
			opid = entity.getId();
			if (StringUtils.isEmpty(entity.getId())) {
				// 创建新对象
				entity.setId(null);
				entity.setDelFlag(Constants.DELFLAG_IN);
				entity.setCreateDate(DateUtils.getCurrentDate());
			} else {
				delFlag = entity.getDelFlag();
			}
		}
		if (StringUtils.isEmpty(opid)) {
			opid = "";
			optype = "新增";
		} else {
			if ("0".equals(delFlag)) {
				optype = "更新";
			} else {
				optype = "删除";
			}
		}
		if (StringUtils.isNotEmpty(username)) {
			MDC.put("id", id);
			MDC.put("username", username);
			MDC.put("classname", classname);
			MDC.put("opid", opid);
			MDC.put("optype", optype);
			logger.info("对" + classname + "对象 在进行" + optype + "操作");
		} else {
//			logger.info("error,用户名或密码错误");
		}
	}

}
